<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    连接地址：<br>
    <input id="url" value="ws://localhost:8080/echo?id=123"><br>
    <button onclick="connect()">连接</button>
    <button onclick="disconnect()">断开</button>
</div>
<div>
    消息：<br>
    <input id="message"><br>
    <button onclick="send()">发送</button>
</div>
<div id="msgBox" style="width: 500px;height: 300px;white-space: pre;border: 1px cornflowerblue" ></div>
<script type="application/javascript">
    const wsBox = document.getElementById("url");
    const wsDisBtn = document.getElementById("disconnect");
    const msg = document.getElementById("message");
    const msgBtn = document.getElementById("send");
    const  msgBox = document.getElementById("msgBox");
    function connect() {
        const ws = new WebSocket(wsBox.value);
        ws.onopen = function (evt) {
            console.log("连接成功……");
            // ws.send("Hello WebSocket First!");
        }

        ws.onmessage = function (evt) {
            console.log("收到消息: ", evt.data)
            msgBox.append(`${evt.data}\n`)
        }
    }

    function send() {
        const api = `http://localhost:8080/msg/send?id=123&data=${msg.value}`;
        fetch(api)
            .then(response => response.text())
            .then(data => console.log(data))
            .catch(error => console.log(error))
    }
</script>
</body>
</html>